package doc.ic.walkmore.toolbox;

/**
 * Implementation of the abstract PeakDetection
 *
 */
public class PeakDetectionMACD extends PeakDetection {

	
	// The two parameters of this algo
	private int slowMeanRate;
	private int fastMeanRate;

	public PeakDetectionMACD() {
		// If no parameters provided use these values
		slowMeanRate = 8;
		fastMeanRate = 12;
	}
	
	public PeakDetectionMACD(int sRate, int fRate) {
		// If no parameters provided use these values
		slowMeanRate = sRate;
		fastMeanRate = fRate;
	}
	
	@Override
	public int countPeaks(double[] values) {		
		double[] macdDiff = new double[values.length];		
		// MACD params
		double mSlow = values[0], mFast = mSlow;
		int rSlow = slowMeanRate;
		int rFast = fastMeanRate;
		int index = 0;
		// zeroCrossCount params
		int res = 0;
		double cur = 0.0, next = 0.0;

		for (int i=0;i<values.length;i++) {
			// -----------------------------------------
			// MACD ALGO
			mSlow = 0.0;mFast = 0.0;
			int mSlowCoef = 0, mFastCoef = 0;
			for (int j=0;j<rFast; j++) {
				index = i - (rFast/2) +j;
				if (index>=0 && index<values.length){
					mFast += values[index];
					mFastCoef++;
					int offset =((rFast-rSlow)/2);
					if ((j >= offset) && (j < offset+rSlow)){
							mSlow += values[index];
							mSlowCoef++;
					}
				}
			}
			mSlow /= (double)mSlowCoef;
			mFast /= (double)mFastCoef;
			
			macdDiff[i] = mFast-mSlow;
			// -----------------------------------------
			
			// -----------------------------------------
			// ZeroCrossCount within the same loop
			if (i>0) {
				cur = macdDiff[i-1];
				next = macdDiff[i];
				if (cur <= 0.) {
					if (next>0.) {
//						res++;
						cur = next;
					}
				}
				if (cur >= 0.){
					if (next < 0.) {
						res++;
						cur = next;
					}
				}
			}
			// -----------------------------------------
		}
		
		return res;
	}



}
